package cn.edu.swu.safety;

import cn.edu.swu.user.USER;
import cn.edu.swu.user.userRepo;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/Login")
public class Login extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        String user = request.getParameter("user");
        String psw = request.getParameter("psw");
        String code = request.getParameter("authcode");
        HttpSession session =request.getSession(true);


        if(code==null||!code.equalsIgnoreCase((String) session.getAttribute(AuthCode.AUTH_CODE))){
            response.sendRedirect("./admin.html");
            return;
        }

        try {
            List<USER> users= userRepo.getInstance().findUser(user,psw);
            if (user != null && !users.isEmpty() && psw != null) {
                //登录成功信息附到session中
                //HttpSession session = request.getSession(true);
                session.setAttribute(AuthFilter.AUTH_STATUS, AuthStatus.LOGIN_SUCCESS);
                response.sendRedirect("./index-simple.html");
            }
            else response.sendRedirect("admin.html");
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

    }
}
